/**
 * @author: quantm.tb@gmail.com/quandaso
 * @module:
 * @version:
 * @date: 11/11/13 2:12 PM
 */
(function($){

    $.fn.create_type_ahead_input = function(fn){
        if(!this.length)
            return _W("*fn: create_type_ahead_input(): " + this.selector + " is n/a!");

        if(!this.is("input"))
            return _W("*fn: create_type_ahead_input(): " + this.selector + " is not a input!");

        var self = this;
        var search_url = self.attr("data-search-ajax");
        if(!search_url )
            return _W("*fn: create_type_ahead_input(): Missing data-search-ajax  " + this.selector);

        var auto_suggest_list = [];
        self.typeahead({source: auto_suggest_list});
        self.keyup(function(e){
            if(e.which == 13){
                if(typeof fn == "function")
                    fn.call(self, self.val());
                return;
            }
            var data = {key: self.val()};
            $.post(search_url, data)
                .done(function(d){
                    var r = $.parseJSON(d);
                    for(var i in r){
                        if(auto_suggest_list.indexOf(r[i]) == -1){
                            auto_suggest_list.push(r[i]);
                        }
                    }
                });
        });
    }

    $.fn.message_box = function(type, message){
        if(!this.length)
            return _W("*fn: message_box(): " + this.selector + " is n/a!");

        type = (type.indexOf("alert") == -1) ? "alert-" + type : type;
        $("#message_box").remove();
        var message_box = '<div id="message_box" style="display: none;" class="alert '+type+'">'+message+'<br/><em style="font-size: 11px;">Click to hide message</em></div>';
        this.prepend(message_box);
        $("#message_box").fadeIn();
        $(document).on("click","#message_box",function(){
            $(this).fadeOut();
        });
    }

    $.fn.post_form = function(fn){
        if(!this.length)
            return _W("*fn: post_form(): " + this.selector + " is n/a!");


        var self = this;
        var HREF = self.attr("data-href");
        if(!HREF){
            HREF = location.href;
            _L('*fn: post_form(): data-href is undefined, use current href: "' + HREF + '" instead');
        }
        this.submit(function(e){
            e.preventDefault();
            var data = get_form_data(self.selector);
            $.post(HREF, data)
                .done(function(d){
                    if(d == "SUCCESS"){
                        if(typeof fn == 'function'){
                            fn.call(self, data);
                        }

                    }else{
                        var msg = d.replace(/<br>$/, '');
                        self.message_box("alert-danger", msg);
                    }
                }).fail(function(j, q){error(q)});
        });
        return self;
    }

})(window.jQuery)

function pr(object){
    //print raw level 1 object
    var output = '';
    for (var p in object) {
        output += p + ' => ' + object[p]+'\n ';
    }
    console.log(output);
    //return output;
}

function make_id(len){
    len = len || 5;
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

function get_param_by_name(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function error(q){
    alert("Có lỗi không xác định!");
    console.warn(q);
}

function _W(s){
    console.warn(s);
    return false;
}

function _L(s){
    console.log(s);
    return true;
}

function is_mobile(){
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function number_format(n, c, d, t){
    var
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function get_form_data(form_selector){
    var  data = {};
    var index = 1;
    //get input data
    $(form_selector + " input").each(function(){
        var name = $(this).attr("name");
        var type = $(this).attr("type");
        if(!name) throw("#err: Expected name attribute at input no." + index);
        if(!type) throw("#err: Expected type attribute at input no." + index);
        index++;
        if(type == "file")
            return true;
        if(type == "checkbox"){
            data[name] = $(form_selector + ' input[name="' + name + '"]').is(":checked") ? 1 : 0;
            return true;
        }
        if(type == "radio"){
            data[name] = $(form_selector + ' input[name="' + name + '"]:checked').val();
            return true;
        }

        data[name] = $(this).val();
    });
    //get select data
    index = 1;
    $(form_selector + " select").each(function(){
        var name = $(this).attr("name");
        if(!name) throw("#err: Expected name attribute at select no." + index);
        data[name] = $(this).val();
        index++;

    });
    //get text area data
    index = 1;
    $(form_selector + " textarea").each(function(){
        var name = $(this).attr("name");
        if(!name) throw("#err: Expected name attribute at textarea no." + index);
        data[name] = $(this).val();
        index++;
    });
    //pr(data);
    return data;
}

